

# 利用pyelftools, 从elf的符号表中读出列出全部符号（符号名、符号地址、符号尺寸）
# pip install pyelftools

from elftools.elf.elffile import ELFFile


syms=[]

fileName="/pubx/build-llvm15/bin/clang-15"
with open(fileName, 'rb') as f:
    elffile = ELFFile(f)

    for sec in elffile.iter_sections():
        print(f'{sec.name},{sec["sh_type"]}')

    """
    ,SHT_NULL
.interp,SHT_PROGBITS
.note.gnu.property,SHT_NOTE
.note.gnu.build-id,SHT_NOTE
.note.ABI-tag,SHT_NOTE
.gnu.hash,SHT_GNU_HASH
.dynsym,SHT_DYNSYM
.dynstr,SHT_STRTAB
.gnu.version,SHT_GNU_versym
.gnu.version_r,SHT_GNU_verneed
.rela.dyn,SHT_RELA
.rela.plt,SHT_RELA
.eh_frame,SHT_PROGBITS
.eh_frame_hdr,SHT_PROGBITS
.rodata,SHT_PROGBITS
.rodata.cst,SHT_PROGBITS
.plt,SHT_PROGBITS
.plt.got,SHT_PROGBITS
.fini,SHT_PROGBITS
.init,SHT_PROGBITS
.text,SHT_PROGBITS
.tbss,SHT_NOBITS
.dynamic,SHT_DYNAMIC
.data.rel.ro,SHT_PROGBITS
.fini_array,SHT_FINI_ARRAY
.init_array,SHT_INIT_ARRAY
.got,SHT_PROGBITS
.relro_padding,SHT_NOBITS
.got.plt,SHT_PROGBITS
.data,SHT_PROGBITS
.tm_clone_table,SHT_PROGBITS
.bss,SHT_NOBITS
.strtab,SHT_STRTAB
.symtab,SHT_SYMTAB
.shstrtab,SHT_STRTAB
.comment,SHT_PROGBITS
.debug_abbrev,SHT_PROGBITS
.debug_aranges,SHT_PROGBITS
.debug_info,SHT_PROGBITS
.debug_line,SHT_PROGBITS
.debug_ranges,SHT_PROGBITS
.debug_str,SHT_PROGBITS
    """



    sec_dynsym=elffile.get_section_by_name(".dynsym")
    sec_symtab=elffile.get_section_by_name(".symtab")

    sec_dynsym_num_symbols=sec_dynsym.num_symbols()
    sec_symtab_num_symbols=sec_symtab.num_symbols()

    for sk in sec_dynsym.iter_symbols():
        symbol_name:str=sk.name
        symbol_addr:int=sk.entry["st_value"]
        symbol_size:int=sk.entry["st_size"]
        # print(f'{symbol_name},{symbol_addr:0x},{symbol_size}\n')
        syms.append( (symbol_name,symbol_addr,symbol_size) )

    """
    _ZZN4llvm10FoldingSetIN5clang23DependentSizedArrayTypeEE17getFoldingSetInfoEvE4Info,10512c20,24
    """

    for sk in sec_symtab.iter_symbols():
        symbol_name:str=sk.name
        symbol_addr:int=sk.entry["st_value"]
        symbol_size:int=sk.entry["st_size"]
        # print(f'{symbol_name},{symbol_addr:0x},{symbol_size}\n')
        syms.append( (symbol_name,symbol_addr,symbol_size) )



symbol_name: str = None
symbol_addr: int = None
symbol_size: int = None
addr:int=0x98ac4a5
for sk in syms:
    symbol_name,symbol_addr,symbol_size=sk
    if addr >= symbol_addr and addr <= symbol_addr+symbol_size:
        print(f"found:{sk}")
        break
